﻿using System.Reflection;
using System.Web.Mvc;
using Autofac;
using Autofac.Integration.Mvc;
using Raven.Client;
using TodoApp.Controllers;
using TodoApp.Models;
using TodoApp.Repositories;
using TodoApp.Repositories.Contract;

namespace TodoApp
{
    public static class Bootstrapper
    {
        public static void Run()
        {
            SetAutofacContainer();
        }

        private static void SetAutofacContainer()
        {
            var builder = new ContainerBuilder();
            var assembly = Assembly.GetAssembly(typeof(HomeController));

            builder.RegisterControllers(assembly);
            builder.Register(x => DataDocumentStore.Initialize()).As<IDocumentStore>().SingleInstance();
            builder.Register(x => x.Resolve<IDocumentStore>().OpenSession()).As<IDocumentSession>()
                   .InstancePerLifetimeScope()
                   .OnRelease(x =>
                       {
                           x.SaveChanges();
                           x.Dispose();
                       });

            builder.RegisterGeneric(typeof(BaseRepository<>)).As(typeof(IRepository<>)).InstancePerLifetimeScope();

            DependencyResolver.SetResolver(new AutofacDependencyResolver(builder.Build()));
        }
    }
}